import { Worker } from 'node:worker_threads'

export default function on(path: string, params?: any, config?: any) {
  return new Promise((resolve, reject) => {
    try {
      console.log(path)

      const worker = new Worker(path, {
        workerData: params,
        ...config,
      })

      let isResolved = false

      const handleMessage = (event: MessageEvent) => {
        if (!isResolved) {
          isResolved = true
          cleanup()
          resolve(event)
        }
      }

      const handleError = (error: Error) => {
        if (!isResolved) {
          isResolved = true
          cleanup()
          reject(error)
        }
      }
      function cleanup() {
        worker.removeListener('message', handleMessage)
        worker.removeListener('error', handleError)
      }
      worker.addListener('message', handleMessage)
      worker.addListener('error', handleError)
    }
    catch (error) {
      reject(error)
    }
  })
}
